package com.millstein.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.millstein.eduservice.entity.EduSubject;
import com.millstein.eduservice.entity.excel.SubjectData;
import com.millstein.eduservice.entity.subject.OneSubject;
import com.millstein.eduservice.entity.subject.TwoSubject;
import com.millstein.eduservice.listener.SubjectExcelListener;
import com.millstein.eduservice.mapper.EduSubjectMapper;
import com.millstein.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-13
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 批量添加课程分类
     * @param file
     */
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            EasyExcel.read(file.getInputStream(),
                    SubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的课程分类，返回格式是树形结构
     *
     * @return
     */
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        // 1.查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", 0);
        List<EduSubject> oneSubjectList = this.list(wrapperOne);

        // 2.查询所有二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", 0);
        List<EduSubject> twoSubjectList = this.list(wrapperTwo);

        // 这个list是最终返回的list
        List<OneSubject> finalSubjectList = new ArrayList<>();
        // 这个map存储的是一级分类id和它在finalSubjectList中索引的对应关系
        Map<String, Integer> map = new HashMap<>();

        // 3.封装一级分类
        for (int i = 0; i < oneSubjectList.size(); i++) {
            EduSubject subject = oneSubjectList.get(i);
            OneSubject one = new OneSubject();
            // 将两个对象的同名属性进行赋值
            BeanUtils.copyProperties(subject, one);
            finalSubjectList.add(one);
            map.put(subject.getId(), i);
        }

        // 4.封装二级分类
        for (EduSubject subject : twoSubjectList) {
            TwoSubject two = new TwoSubject();
            BeanUtils.copyProperties(subject, two);
            finalSubjectList.get(map.get(subject.getParentId())).getChildren().add(two);
        }

        return finalSubjectList;
    }

}
